import { UploadOutlined, UserOutlined } from '@ant-design/icons';
import { Helmet, useModel } from '@umijs/max';
import { App, Button, Card, Form, Input, message, Spin, Upload } from 'antd';
import { createStyles } from 'antd-style';
import { useEffect, useState } from 'react';
import { uploadFileUsingPost } from '@/services/yubi/fileController';
import {
  getLoginUserUsingGet,
  updateMyUserUsingPost,
} from '@/services/yubi/userController';

const useStyles = createStyles(({ token }) => {
  return {
    action: {
      marginLeft: '8px',
      color: 'rgba(0, 0, 0, 0.2)',
      fontSize: '24px',
      verticalAlign: 'middle',
      cursor: 'pointer',
      transition: 'color 0.3s',
      '&:hover': {
        color: token.colorPrimaryActive,
      },
    },
    lang: {
      width: 42,
      height: 42,
      lineHeight: '42px',
      position: 'fixed',
      right: 16,
      borderRadius: token.borderRadius,
      ':hover': {
        backgroundColor: token.colorBgTextHover,
      },
    },
    container: {
      display: 'flex',
      flexDirection: 'column',
      height: '100vh',
      overflow: 'auto',
      backgroundImage:
        "url('https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/V-_oS6r-i7wAAAAAAAAAAAAAFl94AQBr')",
      backgroundSize: '100% 100%',
    },
    avatarPreview: {
      width: '100%',
      maxHeight: 200,
      objectFit: 'contain',
    },
  };
});

/**
 * 个人资料页面
 * @constructor
 */
const AccountPage: React.FC = () => {
  const [loading, setLoading] = useState<boolean>(true);
  const [updating, setUpdating] = useState<boolean>(false);
  const { initialState, setInitialState } = useModel('@@initialState');
  const { styles } = useStyles();
  const { message: msg } = App.useApp();
  const [form] = Form.useForm();
  const [avatarUrl, setAvatarUrl] = useState<string>('');

  /**
   * 获取当前用户信息
   */
  const fetchUserInfo = async () => {
    try {
      setLoading(true);
      const res = await getLoginUserUsingGet();
      if (res.data) {
        // 设置表单默认值
        form.setFieldsValue({
          userName: res.data.userName,
          userAccount: res.data.userAccount, // 修复字段名
          userAvatar: res.data.userAvatar,
        });
        setAvatarUrl(res.data.userAvatar || '');
      }
    } catch (e: any) {
      msg.error('获取用户信息失败: ' + e.message);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchUserInfo();
  }, []);

  /**
   * 更新用户信息
   * @param values
   */
  const onFinish = async (values: any) => {
    try {
      setUpdating(true);
      // 如果没有修改密码，则不传递空密码
      if (!values.userPassword) {
        delete values.userPassword;
      }
      if (!values.checkPassword) {
        delete values.checkPassword;
      }

      const res = await updateMyUserUsingPost(values);
      if (res.code === 0) {
        msg.success('更新成功');
        // 更新全局状态
        setInitialState({
          ...initialState,
          currentUser: { ...initialState?.currentUser, ...values },
        });
        // 更新头像预览
        if (values.userAvatar) {
          setAvatarUrl(values.userAvatar);
        }
      } else {
        msg.error('更新失败: ' + res.message);
      }
    } catch (e: any) {
      msg.error('更新失败: ' + e.message);
    } finally {
      setUpdating(false);
    }
  };

  const handleAvatarChange = async ({ fileList }: any) => {
    if (fileList && fileList.length > 0) {
      const file = fileList[0].originFileObj;
      if (file) {
        try {
          // 使用现有的文件上传接口，添加biz参数指定业务类型为用户头像
          const res = await uploadFileUsingPost(
            { biz: 'user_avatar' },
            {},
            file,
          );
          if (res.code === 0) {
            const url = res.data;
            setAvatarUrl(url);
            form.setFieldsValue({ userAvatar: url });
            msg.success('头像上传成功');
          } else {
            msg.error('头像上传失败: ' + res.message);
          }
        } catch (e: any) {
          msg.error('头像上传失败: ' + e.message);
        }
      }
    }
  };

  return (
    <div className="account-page">
      <Helmet>
        <title>个人资料</title>
      </Helmet>
      <Card title="个人资料">
        <Spin spinning={loading}>
          <Form
            form={form}
            name="accountForm"
            labelAlign="left"
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 16 }}
            onFinish={onFinish}
          >
            <Form.Item
              name="userName"
              label="用户名"
              rules={[{ required: true, message: '请输入用户名' }]}
            >
              <Input placeholder="请输入用户名" prefix={<UserOutlined />} />
            </Form.Item>

            <Form.Item
              name="userAccount"
              label="账号"
              rules={[{ required: true, message: '请输入账号' }]}
            >
              <Input placeholder="请输入账号" disabled />
            </Form.Item>

            {/* 头像展示和上传 */}
            <Form.Item label="头像">
              {avatarUrl && (
                <img
                  src={avatarUrl}
                  alt="头像预览"
                  className={styles.avatarPreview}
                />
              )}
              <Form.Item name="userAvatar" noStyle>
                <Input placeholder="请输入头像地址或上传图片" />
              </Form.Item>
              <Upload
                listType="picture"
                maxCount={1}
                beforeUpload={() => false} // 阻止自动上传
                onChange={handleAvatarChange}
              >
                <Button icon={<UploadOutlined />}>上传头像</Button>
              </Upload>
            </Form.Item>

            {/* 修改密码部分 */}
            <Form.Item name="userPassword" label="新密码">
              <Input.Password placeholder="不修改请留空" />
            </Form.Item>

            <Form.Item
              name="checkPassword"
              label="确认密码"
              dependencies={['userPassword']}
              rules={[
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (!value || getFieldValue('userPassword') === value) {
                      return Promise.resolve();
                    }
                    return Promise.reject(new Error('两次输入的密码不一致!'));
                  },
                }),
              ]}
            >
              <Input.Password placeholder="请再次输入新密码" />
            </Form.Item>

            <Form.Item wrapperCol={{ span: 12, offset: 4 }}>
              <Button
                type="primary"
                htmlType="submit"
                loading={updating}
                disabled={updating}
              >
                更新信息
              </Button>
            </Form.Item>
          </Form>
        </Spin>
      </Card>
    </div>
  );
};

export default AccountPage;
